﻿using System;
using System.Collections.Generic;
using cfg.Myskill;
using cfg.skill;
using Events.EventsInfo;
using UnityEngine;
using UnityEngine.Events;

public class SwordCloneController:CloneController
{
    
    private ThrowSword info;
    private bool canRate;
    private bool isReturning ;
    // 弹跳信息
    private int bounceCount;//弹跳次数
    private Collider2D bounceTarget;//弹跳的目标
    
    //穿透信息
    private int penetrationCount;
    private Collider2D oldPierceTarget;//上一次的被穿透目标
    
    //旋转信息
    private bool canRotate;
    private bool stopMove;
    

    private void ReturnSword()
    {
        //ReSet();
        isReturning = true;
    }
    
    public override void Init(CloneBase _info, Vector2 pos, int faceDir)
    {
        base.Init(_info, pos, faceDir);
        info = _info.ToSubClass<ThrowSword>();
        //注册事件监听
        EventCenter.Instance.AddEventListener(E_EventType.Sword_StartReturn, ReturnSword);
        Reset();
        //disapperSpeed = 5;
    }

    protected override void DestroySelf()
    {
        //取消事件监听
        EventCenter.Instance.RemoveEventListener(E_EventType.Sword_StartReturn, ReturnSword);
        //通知技能层返回结束
        EventCenter.Instance.EventTrigger(E_EventType.Sword_FinishReturn,new ReturnSwordInfo()
        {
            returnDir =  1,
            notEnterCatchState = true//不展示接剑姿势
        });
        base.DestroySelf();
        
    }

    public override void Reset()
    {
        canRate = true;
        cd.enabled = true;
        rb.bodyType = RigidbodyType2D.Dynamic;
        rb.constraints = RigidbodyConstraints2D.None;
        rb.gravityScale = info.SwordGravity;
        transform.right = Vector3.right;
        transform.parent = null;
        disapperSpeed = 5;
        
        //重置弹跳信息
        bounceTarget = null;
        bounceCount = 0;
        
        //重置穿透信息
        penetrationCount = 0;
        oldPierceTarget = null;
        
        //重置旋转信息
        canRotate = false;
        stopMove  = false;
    }

    public void AddForce(Vector2 dir)
    {
        var throwForce = info.ThrowForce;
        if (throwForce!=0)
        {
            rb.AddForce(new Vector2(dir.x* throwForce, dir.y* throwForce*1.5f),ForceMode2D.Impulse);
            
        }
    }

    protected override void Update()
    {
        base.Update();
        if (canRate)
        {
            transform.right = rb.velocity;
        }
        if (isReturning)
        {
            Play("sword_flip");
            //isReturning = false;
            transform.position =
                Vector3.MoveTowards(transform.position, controller.transform.position, 30 * Time.deltaTime);
            if (Vector3.Distance(transform.position, controller.transform.position) < 0.2f)
            {
                FinishSwordSkill(true);
            }
        }

        if (bounceTarget!=null&&bounceCount>0)
        {
            BounceUpdate();
        }

        if (penetrationCount>0)
        {
            PierceUpdate();
        }

        if (canRotate)
        {
            //旋转
            RoateUpdate();
        }
    }

    public void FinishSwordSkill(bool canCatch)
    {
        //base.TriggerFinish();
        isReturning = false;
        //计算返回方向
        if (canCatch)
        {
            var dir = transform.position.x > controller.transform.position.x?1:-1;
            //通知技能层结束
            EventCenter.Instance.EventTrigger(E_EventType.Sword_FinishReturn,new ReturnSwordInfo()
            {
                returnDir =  dir
            });
            
        }
        else
        {
            EventCenter.Instance.EventTrigger(E_EventType.Sword_FinishReturn,new ReturnSwordInfo()
            {
                returnDir =  1,
                notEnterCatchState = true//不展示接剑姿势
            });
        }
        DestroySelf();
    }
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (bounceCount>0)
        {
            BounceTrigger(other);//弹跳剑会关闭碰撞检测 这里只走一次
            
        }else if (penetrationCount>0)
        {
            PierceTrigger(other);
        }else if (canRotate)
        {
            RoateTrigger(other);
        }
        else
        {
            Damage(other);
            TryFinishSwordFly(other);
            
        }
    }

    private void TryFinishSwordFly(Collider2D other=null)
    {
        rb.bodyType = RigidbodyType2D.Kinematic;
        rb.constraints = RigidbodyConstraints2D.FreezeAll;
        canRate = false;
        cd.enabled = false;
        //设置刀刃停留方向    
        /*var dir = transform.position.x > controller.transform.position.x?1:-1;
        transform.right = Vector2.right*dir;*/
        Play("sword_idle");
        transform.parent = other!=null ? other.transform : null;
        //通知技能层可以返回
        EventCenter.Instance.EventTrigger(E_EventType.Sword_CanReturn);
        
    }
    
    private void Damage(Collider2D other)
    {
        EnemyStateController enemyStateController = other.GetComponent<EnemyStateController>();
        if (enemyStateController != null)
        {
            //计算击退方向
            var dir = transform.position.x < other.transform.position.x?1:-1;
            var hitBackForce = info.HitBackForce;
            enemyStateController.Damage(new DamgeInfo()
            {
                damage = controller.GetDamage()+info.SkillDamage,
                attacker = controller.characterBase,
                targeter = enemyStateController.characterBase,
                hitBackForce = new  Vector2(dir* hitBackForce, hitBackForce*0.5f),
                hitBackTime = 0.2f,
            });
        }
    }

    #region 弹跳剑
    public void CanBounce()
    {
        bounceCount = skillInfo.ToSubClass<ThrowSword>().AttackCount;
    }
    
    private void BounceUpdate()
    {
        transform.position =
            Vector3.MoveTowards(transform.position, bounceTarget.transform.position, 20 * Time.deltaTime);
        if (Vector3.Distance(transform.position, bounceTarget.transform.position) < 0.5f)
        {
            TryFindBounceTarget(bounceTarget);
        }
    }
    
    private void BounceTrigger(Collider2D other)
    {
        rb.bodyType = RigidbodyType2D.Kinematic;
        rb.constraints = RigidbodyConstraints2D.FreezeAll;
        canRate = false;
        cd.enabled = false;
        //如果可以弹跳
        if (bounceCount>0)
        {
            if (other.gameObject.layer  == LayerMask.NameToLayer("Enemy"))
            {
                //查找第一个弹跳目标
                if (bounceTarget==null)
                {
                    TryFindBounceTarget(other);
                }
            
            }
            else
            {
                bounceCount = 0;
            }
        }

        if (bounceCount<=0)
        {
            TryFinishSwordFly(other);
        }

    }
    
    private void TryFindBounceTarget(Collider2D other)
    {
        Damage(other);
        //从当前位置以半径为10的圆形区域找到最近的敌人
        var enemys = Physics2D.OverlapCircleAll(transform.position, 10, LayerMask.GetMask("Enemy"));
        var  minDis = float.MaxValue;
        foreach (var enemy in enemys)
        {
            var dis = Vector3.Distance(transform.position, enemy.transform.position);
            if (dis<minDis&&other!=enemy)
            {
                minDis = dis;
                bounceTarget = enemy;
            }
        }
        if (bounceTarget==null)
        {
            //如果没找到，则结束弹跳
            bounceCount = 0;
        }
        else
        {
            bounceCount--;
        }

        if (bounceCount<=0)
        {
            TryFinishSwordFly(other);
        }
    }
    #endregion


    #region 穿透剑

    public void CanPierce()
    {
        penetrationCount = info.AttackCount;
        Debuger.Log("canPierce"+penetrationCount);
    }
    private void PierceUpdate()
    {
        //离玩家距离30后停止
        if (Vector3.Distance(transform.position, controller.transform.position) > 50)
        {
            penetrationCount = 0;
            TryFinishSwordFly();
        }
    }
    private void PierceTrigger(Collider2D other)
    {
        if (penetrationCount>0)
        {
            if (other.gameObject.layer == LayerMask.NameToLayer("Enemy"))
            {
                if (oldPierceTarget==null||oldPierceTarget!=other)
                {
                    Damage(other);
                    oldPierceTarget = other;
                    penetrationCount--;
                }
            }
            else  // 如果遇到非敌人，则结束
            {
                penetrationCount = 0;
            }
        }

        if (penetrationCount<=0)
        {
            TryFinishSwordFly(other);
        }
    }
    #endregion

    #region 旋转剑
    public void CanRotate()
    {
        canRotate = true;
    }
    
    private void RoateTrigger(Collider2D other)
    {
        //停在原地旋转
        if (!stopMove)
        {
            stopMove = true;
            rb.velocity = Vector2.zero;
        }
        Damage(other);
    }
    
    private void RoateUpdate()
    {
        //z轴上旋转自己
        if (stopMove)
        {
            transform.Rotate(Vector3.forward*Time.deltaTime*90);
        }
        else
        {
            //离玩家距离30后停止
            if (Vector3.Distance(transform.position, controller.transform.position) > 30)
            {
                FinishSwordSkill(false);
            }
            
        }
        
        
    }
    #endregion
    
}